package appllo5;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerWin {
    public static void main(String[] args) {
        // 监听指定的端口
        int port = 8888;
        ServerSocket server = null;
        try {
            server = new ServerSocket(port);
            System.out.println("服务启动");
        } catch (IOException e) {
            e.printStackTrace();
        }

        while (true) {
            // server将一直等待连接的到来
            Socket socket = null;
            try {
                socket = server.accept();
                socket.setKeepAlive(true);
                socket.setSoTimeout(300 * 1000);
                new Thread(new Task(socket)).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static class Task implements Runnable {
        private Socket socket;

        public Task(Socket socket) throws IOException {
            this.socket = socket;
        }

        @Override
        public void run() {
            // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
            try {

                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                Writer writer = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");

                byte[] bytes = new byte[1024];
                String input = br.readLine();
                String bb = "welcome new client";
                writer.write(bb);
                writer.flush();
                System.out.println("get message from client: " + input);
                br.close();
                writer.close();
                socket.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
